#include "sock_mgr.h"

const std::vector<HandleContent>& SockMgr::GetHandleContents()
{
    m_retOfHandleContents.clear();
    std::lock_guard<std::mutex> guard(m_mutex);
    for (auto it = m_handlers.begin(); it != m_handlers.end(); ++it)
        m_retOfHandleContents.push_back(it->second);

    return m_retOfHandleContents;
}

const std::vector<herm::ISockHandler*>& SockMgr::GetHandlers()
{
    m_retOfhandlers.clear();
    std::lock_guard<std::mutex> guard(m_mutex);
    for (auto it = m_handlers.begin(); it != m_handlers.end(); ++it)
        m_retOfhandlers.push_back(it->second.handler);

    return m_retOfhandlers;
}

void SockMgr::Add(herm::ISockHandler* eh, herm::MultiplexorMask mask)
{
    std::lock_guard<std::mutex> guard(m_mutex);
    // Set except when registering
    HandleContent hc;
    hc.handler = eh;
    hc.mask = mask | herm::Private::EXCEPT_MASK;
    m_handlers.insert(std::make_pair(eh->OnGetHandle(), hc));
}

void SockMgr::Remove(herm::ISockHandler* eh)
{
    std::lock_guard<std::mutex> guard(m_mutex);
    m_removedSocks.push_back(eh->OnGetHandle());
}

const std::vector<herm::ISockHandler*>& SockMgr::HandleRemove()
{
    m_retOfhandlers.clear();

    std::lock_guard<std::mutex> guard(m_mutex);
    for (auto it = m_removedSocks.begin(); it != m_removedSocks.end(); ++it)
    {
        EventHandlers::iterator handlerIt = m_handlers.find(*it);
        if (handlerIt != m_handlers.end())
        {   
            m_retOfhandlers.push_back(handlerIt->second.handler);
            m_handlers.erase(handlerIt);
        }
    }

    m_removedSocks.clear();

    return m_retOfhandlers;
}

void SockMgr::EnableMask(herm::ISockHandler* eh, herm::MultiplexorMask mask)
{
    std::lock_guard<std::mutex> guard(m_mutex);
    EventHandlers::iterator it = m_handlers.find(eh->OnGetHandle());
    if (it != m_handlers.end())
        it->second.mask |= mask;
}

void SockMgr::DisableMask(herm::ISockHandler* eh, herm::MultiplexorMask mask)
{
    std::lock_guard<std::mutex> guard(m_mutex);
    EventHandlers::iterator it = m_handlers.find(eh->OnGetHandle());
    if (it != m_handlers.end())
        it->second.mask &= ~mask;
}